package cn.stylefeng.guns.modular.rest.mdbh;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.entity.StoreAccount;
import cn.stylefeng.guns.modular.basic.model.params.StoreAccountParam;
import cn.stylefeng.guns.modular.basic.model.params.StoreAccountRecordParam;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoodsCode;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsCodeService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutParam;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.storeProcurement.entity.StoreProcurementDetaild;
import cn.stylefeng.guns.modular.storeProcurement.model.params.StoreProcurementDetaildParam;
import cn.stylefeng.guns.modular.storeProcurement.model.params.StoreProcurementParam;
import cn.stylefeng.guns.modular.storeProcurement.model.result.StoreProcurementDetaildResult;
import cn.stylefeng.guns.modular.storeProcurement.service.StoreProcurementDetaildService;
import cn.stylefeng.guns.modular.storeProcurement.service.StoreProcurementService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 补货
 * 主要用于补货的列表展示
 * @author wp
 * @date 2025-03-22
 */
@Controller
@RequestMapping("/rest/mdbh")
public class restMdBhController extends BaseController {

    @Autowired
    private UserAop userAop;
    @Autowired
    private DeptService deptService;

    @Autowired
    private StoreProcurementService storeProcurementService;

    @Autowired
    private StoreProcurementDetaildService storeProcurementDetaildService;

    @Autowired
    private StoreAccountService storeAccountService;

    @Autowired
    private StoreAccountRecordService storeAccountRecordService;

    @Autowired
    private HxOrderOutService hxOrderOutService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private HxOrderOutDetailedService hxOrderOutDetailedService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;


    /**
     * 门店补货列表
     * @param storeProcurementParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/mdbhList")
    public LayuiPageInfo list(StoreProcurementParam storeProcurementParam, String condition) {
        User user = userAop.getUser();
        Long deptId = user.getDeptId();
//        storeProcurementParam.setOrderState("待提交");
        storeProcurementParam.setDeptId(deptId);
        return this.storeProcurementService.findPageByStore(storeProcurementParam,condition);
    }


    /**
     * 根据ID获取补货单信息
     * @param orderOutputNumber
     * @return
     */
    @ResponseBody
    @RequestMapping("/goodsList")
    public LayuiPageInfo goodsList(String orderOutputNumber) {
        StoreProcurementDetaildParam storeProcurementDetaildParam = new StoreProcurementDetaildParam();
        storeProcurementDetaildParam.setOrderOutNumber(orderOutputNumber);
        LayuiPageInfo pageBySpec = storeProcurementDetaildService.findPageBySpec(storeProcurementDetaildParam, null);
        return pageBySpec;
    }

    /**
     * 所有商品列表
     * @param orderOutputNumber
     * @return
     */
    @ResponseBody
    @RequestMapping("/allGoodsList")
    public LayuiPageInfo allGoodsList(String orderOutputNumber) {
        StoreProcurementDetaildParam storeProcurementDetaildParam = new StoreProcurementDetaildParam();
        storeProcurementDetaildParam.setOrderOutNumber(orderOutputNumber);
        LayuiPageInfo pageBySpec = storeProcurementDetaildService.findGoodsPageBySpec(storeProcurementDetaildParam, null);
        return pageBySpec;
    }

    /**
     * 添加商品到补货单
     * @param storeProcurementDetaildParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/addGoodsItem")
    public ResponseData addGoodsItem(StoreProcurementDetaildParam storeProcurementDetaildParam) {

        List<StoreProcurementDetaildResult> detaildResults =  this.storeProcurementDetaildService.findListByGoodsId(storeProcurementDetaildParam.getOrderOutNumber(),storeProcurementDetaildParam.getGoodsId());
        if(detaildResults.size() > 0){
            return ResponseData.error("该商品已经添加到补货单中");
        }
        this.storeProcurementDetaildService.add(storeProcurementDetaildParam);
        return ResponseData.success();
    }

    /**
     * 删除商品
     * @param storeProcurementDetaildParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteGoodsItem")
    public ResponseData deleteGoodsItem(StoreProcurementDetaildParam storeProcurementDetaildParam) {
        this.storeProcurementDetaildService.deleteByGoodsId(storeProcurementDetaildParam);
        return ResponseData.success();
    }


    /**
     * 提交订单
     * @param itemList
     * @return
     */
    @ResponseBody
    @RequestMapping("/submitOrder")
    public ResponseData submitOrder(@RequestBody List<StoreProcurementDetaildParam> itemList) {
        StoreProcurementDetaildParam storeProcurementDetaildParam = itemList.get(0);
        String orderOutNumber = storeProcurementDetaildParam.getOrderOutNumber();
        StoreProcurementParam storeProcurementParam = new StoreProcurementParam();
        storeProcurementParam.setOrderOutNumber(orderOutNumber);
        storeProcurementParam.setOrderState("待审核");
        storeProcurementParam.setSubmitTime(new Date());
        this.storeProcurementService.updateOrderState(storeProcurementParam);
        List<StoreProcurementDetaild> detaildList = new ArrayList<StoreProcurementDetaild>();
        itemList.forEach(item -> {
            StoreProcurementDetaild detaild = new StoreProcurementDetaild();
            BeanUtils.copyProperties(item, detaild);
            detaildList.add(detaild);
        });
        StoreProcurementDetaild storeProcurementDetaild = new StoreProcurementDetaild();
        storeProcurementDetaild.setOrderOutNumber(orderOutNumber);
        this.storeProcurementDetaildService.saveOrUpdateBatch(detaildList);
        return ResponseData.success();
    }

    /**
     * 审核订单
     * @param storeProcurementParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/approvalOrder")
    public ResponseData approvalOrder(StoreProcurementParam storeProcurementParam) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = dateFormat.format(new Date());
        User user = userAop.getUser();
        storeProcurementParam.setV1(user.getName());//审核人
        storeProcurementParam.setV2(timestamp);//审核时间
        this.storeProcurementService.updateOrderState(storeProcurementParam);

        return ResponseData.success();
    }


    /**
     * 支付订单
     * @param storeProcurementParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/paymentOrder")
    public ResponseData paymentOrder(StoreProcurementParam storeProcurementParam) {

        //查询账户余额
        StoreAccount byAccount = this.storeAccountService.getByAccount(null, storeProcurementParam.getGetUnitId().intValue());
       if(byAccount == null){
           return ResponseData.error("账户不存在");
       }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = dateFormat.format(new Date());
        User user = userAop.getUser();
        storeProcurementParam.setV3(user.getName());//支付人
        storeProcurementParam.setV4(timestamp);//支付时间

        // 增加订单支付记录
        StoreAccountRecordParam storeAccountRecordParam  = new StoreAccountRecordParam();
        storeAccountRecordParam.setAccount(storeProcurementParam.getOrderOutNumber());
        storeAccountRecordParam.setType("订单支付");
        storeAccountRecordParam.setAccount(byAccount.getAccount());
        storeAccountRecordParam.setStoreId(storeProcurementParam.getGetUnitId().intValue());//门店ID
        storeAccountRecordParam.setStoreName(byAccount.getStoreName());//门店名称
        storeAccountRecordParam.setAmount(new BigDecimal(storeProcurementParam.getOrderAmount()));//金额
        BigDecimal subtract = byAccount.getRemainingSum().subtract(new BigDecimal(storeProcurementParam.getOrderAmount()));//余额
        storeAccountRecordParam.setRemainingSum(subtract);//余额
        storeAccountRecordParam.setCreateBy(user.getName());
        this.storeAccountRecordService.add(storeAccountRecordParam);

        // 扣减账户金额
        StoreAccountParam storeAccountParam = new StoreAccountParam();
        storeAccountParam.setAccount(byAccount.getAccount());
        storeAccountParam.setRemainingSum(subtract);//余额
        storeAccountParam.setUpdateBy(user.getName());
        storeAccountParam.setUpdateTime(new Date());
        this.storeAccountService.updateByAccount(storeAccountParam);

        //生成仓库出库单
        HxOrderOutParam hxOrderOutParam = new HxOrderOutParam();
        BeanUtils.copyProperties(storeProcurementParam, hxOrderOutParam);
        ResponseData responseData = addItem(hxOrderOutParam);

        //生成仓库出库单明细
        ResponseData responseData1 = addItemDetail(hxOrderOutParam);

        // 更新订单状态
        this.storeProcurementService.updateOrderState(storeProcurementParam);
        return ResponseData.success();
    }



    public ResponseData addItem(HxOrderOutParam hxOrderOutParam) {
        User user = userAop.getUser();
        String trayCode = getOperateIdOrderPrefix(user);
        if(ToolUtil.isNotEmpty(hxOrderOutParam.getOrderOutNumber())) {
            //校验客户单号 是否存在
            if (this.hxOrderOutService.checkCustomerOrder(hxOrderOutParam.getOrderOutNumber())) {
                return ResponseData.error("单号已存在");
            }
        } else {
            hxOrderOutParam.setOrderOutNumber(trayCode+"CK"+ DateUtil.getDatesBch()+DateUtil.getRandomNumber());
        }
        Object WarehouseId = hxOrderOutParam.getSetWarehouseId();
        if (WarehouseId!=null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxOrderOutParam.setSetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxOrderOutParam.getCustomerId();
        if (CustomerId!=null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxOrderOutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        Object setUnitId = hxOrderOutParam.getSetUnitId();
        if (setUnitId!=null) {
            BasicPutgoods basicPutgoods = basicPutgoodsService.getById(Integer.parseInt(setUnitId.toString()));
            hxOrderOutParam.setSetUnit(basicPutgoods.getPutgoodsName());
        }
        Object getUnitId = hxOrderOutParam.getGetUnitId();
        if (getUnitId!=null) {
            BasicPutgoods basicPutgoods = basicPutgoodsService.getById(Integer.parseInt(getUnitId.toString()));
            hxOrderOutParam.setGetUnit(basicPutgoods.getPutgoodsName());
        }
        hxOrderOutParam.setDeptId(user.getDeptId());
        hxOrderOutParam.setDeliverId(user.getDeliverId());
        hxOrderOutParam.setOrderState("待提交");//set 单据状态
        hxOrderOutParam.setCreateUserName(user.getName());//set 制单用户名称
        this.hxOrderOutService.add(hxOrderOutParam);
        return ResponseData.success();
    }

    public ResponseData addItemDetail(HxOrderOutParam hxOrderOutParam) {
        String orderOutNumber = hxOrderOutParam.getOrderOutNumber();
        List<StoreProcurementDetaildResult> detaildResults = this.storeProcurementDetaildService.findListByGoodsId(orderOutNumber,null);
        HxOrderOutDetailedParam hxOrderOutDetailedParam = new HxOrderOutDetailedParam();
        for (StoreProcurementDetaildResult detaildResult : detaildResults) {
            BeanUtils.copyProperties(detaildResult, hxOrderOutDetailedParam);
            Long goodsId = detaildResult.getGoodsId();
            //查询商品信息

            HxBasicGoods hxBasicGoods = hxBasicGoodsService.getById(goodsId);
            hxBasicGoods.getGoodsName();
            hxOrderOutDetailedParam.setPsNum(detaildResult.getPsNum().toString());
            hxOrderOutDetailedParam.setGoodsSpecs(hxBasicGoods.getGoodsSpecs());//规格
            hxOrderOutDetailedParam.setUnit(hxBasicGoods.getCgUnit());//采购单位
            hxOrderOutDetailedParam.setRate(hxBasicGoods.getCgRate());//采购比率
            hxOrderOutDetailedParam.setGoodsVolume(hxBasicGoods.getGoodsVolume());//商品体积
            hxOrderOutDetailedParam.setGoodsWeight(hxBasicGoods.getGoodsWeight());//商品重量
            hxOrderOutDetailedParam.setJibenNum(String.valueOf(BigDecimal.valueOf(detaildResult.getPsNum()).multiply(BigDecimal.valueOf(Double.valueOf(hxBasicGoods.getCgRate())))));//;//商品单价
            hxOrderOutDetailedParam.setJibenUnit(hxBasicGoods.getJibenUnit());//hxBasicGoods.getJiaohuoPrice());//加工单价
            this.hxOrderOutDetailedService.add(hxOrderOutDetailedParam);
        }

        return ResponseData.success();
    }

    public String getOperateIdOrderPrefix(User user) {
        if(user.getOperateId() != null) {
            Dept dept = new Dept();
            dept.setOperateId(user.getOperateId());
            Dept resdept = deptService.findBySpec(dept);
            if(resdept != null) {
                if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
                    return resdept.getOrderPrefix();
                } else {
                    return user.getAccount().substring(0, 3);
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }


}
